//
//  DataManager.m
//  ELibary
//
//  Created by luoz on 15/8/12.
//  Copyright (c) 2015年 luoz. All rights reserved.
//

#import "DataManager.h"

@interface DataManager()

@property(nonatomic, readonly) NSString *dbPath;

@end

@implementation DataManager
@synthesize dbPath = _dbPath;

+ (instancetype)shareManager
{
    static DataManager *dataManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dataManager = [[self alloc] init];
    });
    
    return dataManager;
}

- (id)init
{
    self = [super init];
    if(self){
        db = [FMDatabase databaseWithPath:self.dbPath];
        [db open];
    }
    return self;
}

#pragma mark -Private
- (NSString *)dbPath
{
    if(_dbPath == nil){
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString* bundleID         = [[NSBundle mainBundle] bundleIdentifier];
        NSString *appGroupName     = bundleID;
        
        NSURL *groupContainerURL   = [fileManager containerURLForSecurityApplicationGroupIdentifier:appGroupName];
        
        if([[NSFileManager defaultManager] fileExistsAtPath:groupContainerURL.path]){
            _dbPath = [groupContainerURL.path stringByAppendingPathComponent:@"elibray.sqlite"];
        }
        else{
            NSError* theError = nil;
            if ([fileManager createDirectoryAtURL: groupContainerURL withIntermediateDirectories:YES attributes:nil error:&theError]) {
                _dbPath = [groupContainerURL.path stringByAppendingPathComponent:@"elibray.sqlite"];
            }
            else{
                NSLog(@"error:%@",theError.description);
            }
        }
    }
    return _dbPath;
}


@end
